package com.example.courseapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.courseapp.R;
import com.example.courseapp.RetrofitHelper;
import com.example.courseapp.SharedPreferencesHelper;
import com.example.courseapp.bean.LoginInfo;
import com.example.courseapp.bean.LoginRsp;
import com.example.courseapp.bean.Response;
import com.example.courseapp.net.CourseService;

import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;


/**
 * 登录界面
 * Activity之间如何传递参数
 */
public class LoginActivity extends AppCompatActivity {


    EditText userName, password;

    Button login;

    TextView register;

    CheckBox savePassWord;

    CourseService courseService;


    private ActivityResultLauncher<Intent> activityResultLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        courseService = RetrofitHelper.getInstance().createService(CourseService.class);

        setContentView(R.layout.activity_login);

        userName = findViewById(R.id.user_name);

        password = findViewById(R.id.password);

        login = findViewById(R.id.login);

        register = findViewById(R.id.register);

        savePassWord = findViewById(R.id.save_password);


        String pass = SharedPreferencesHelper.getName(this, "pass");

        if (pass.equals("save")) {
            savePassWord.setChecked(true);
            String mPassword = SharedPreferencesHelper.getName(this, "password");
            password.setText(mPassword);
        }

        savePassWord.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                SharedPreferencesHelper.saveName(this, "pass", "save");
                SharedPreferencesHelper.saveName(this, "password", password.getText().toString());
            } else {
                SharedPreferencesHelper.saveName(this, "pass", "no");
            }

        });

        String str = SharedPreferencesHelper.getName(this, "userName");
        if (!str.isEmpty()) {
            userName.setText(str);
        }

        /*
        通过registerForActivityResult 这个方法跳转从 LoginActivity 跳转到 RegisterActivity，
        在从 RegisterActivity 返回 LoginActivity 时，可以从 RegisterActivity 带回自己想要的参数
         */
        activityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            // 处理从 RegisterActivity 返回的结果
                            Intent data = result.getData();
                            assert data != null;
                            String resultValue = data.getStringExtra("userName");

                            // 处理返回的数据
                            userName.setText(resultValue);
                        }

                    }
                });


        register.setOnClickListener(view -> {
            Intent intent = new Intent(this, RegisterActivity.class);
            // 使用ActivityResultLauncher启动RegisterActivity
            activityResultLauncher.launch(intent);
        });


        login.setOnClickListener(view -> {
            /*
            从 LoginActivity 跳转到 MainActivity 并且将自己想要的数据带到 MainActivity 去
             */

            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setUsername(userName.getText().toString());
            loginInfo.setPassword(password.getText().toString());

            courseService.login(loginInfo).enqueue(new Callback<Response<LoginRsp>>() {
                @Override
                public void onResponse(@NonNull Call<Response<LoginRsp>> call, @NonNull retrofit2.Response<Response<LoginRsp>> response) {
                    Response<LoginRsp> loginRsp = response.body();
                    boolean isLogin = loginRsp.getData() != null;
                    if (isLogin) {
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.putExtra("userName", userName.getText().toString());

                        SharedPreferencesHelper.saveName(LoginActivity.this, "userName", userName.getText().toString());
                        SharedPreferencesHelper.saveName(LoginActivity.this, "userID", loginRsp.getData().getUserId().toString());

                        if (savePassWord.isChecked())//记住密码
                            SharedPreferencesHelper.saveName(LoginActivity.this, "password", password.getText().toString());

                        startActivity(intent);
                        finish();
                    } else {
                        runOnUiThread(() -> {
                            Toast.makeText(LoginActivity.this, "帐号或密码错误", Toast.LENGTH_SHORT).show();
                        });
                    }
                }

                @Override
                public void onFailure(Call<Response<LoginRsp>> call, Throwable t) {
                    Log.d("TAG", "onFailure: " + t);
                }
            });


        });

    }


}